//onshow 获取缓存中的数据
import { require } from '../../require/index.js'
import {getSetting, chooseAddress, openSetting, showToast, requestPayment} from '../../utils/asyncWx.js'
import  regeneratorRuntime from '../../lib/runtime/runtime.js'
Page({
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    toatlNum:0
  },
  onShow() {
    let address = wx.getStorageSync('address');
    let cart = wx.getStorageSync('cart')||[]
    // const allCheck = cart.length?cart.every(v => v.isChecked):false
    cart = cart.filter(v => v.isChecked)
    
    let allCheck = true
    //重数量，总价格
    let  totalPrice = 0
    let toatlNum = 0
    cart.forEach(v => {
      totalPrice += v.num*v.goods_price
      toatlNum += v.num
    })
    this.setData({
      cart,
      toatlNum,
      totalPrice,
      address
    })
    wx.setStorageSync('cart', cart);
  }
  ,
  onLoad: function (options) {

  },
  async pay(){
    try {
      const token = wx.getStorageSync('token')
      if(!token){
        // const res = await require({url: '/users/wxlogin'})
        // console.log(res)
        wx.navigateTo({
          url: '/pages/auth/auth'
        })
        return
      }
      const header = {Authorization: token}
      const order_price = this.data.totalPrice
      const consignee_addr = this.data.address
      const goods = []
      this.data.cart.forEach(v => {
        goods.push({
          goods_id: v.goods_id,
          goods_number: v.num,
          goods_price: v.goods_price
        })
      })
      const orderParams = {order_price, consignee_addr, goods}
      // 返回订单编号
      const {order_number} = await require({url: '/orders/create',method: "post",data: orderParams, header })
      console.log(res)
      // 发起预支付接口
      const { pay } = await require({url: "/my/orders/req_unifiedorder", method: "post", header,data:{order_number}})
      let res1 = await requestPayment(pay)
      console.log(res1)
      // 7查看订单状态
      
      const res2 = await require({url: "/my/orders/chkOrder", method: "post", header,data:{order_number}})
      console.log(res2)
      await showToast({title: '支付成功'})
      // 手动删除已近付了商品
      let newCart = wx.getStorageSync('cart');
      newCart = mewCart.filter(v => !v.isChecked)
      ws.setStorageSync('cart', newCart)
     // 8.支付成功跳到订单页面
     wx.navigateTo({
       url: '',
       success: (result)=>{
         
       },
       fail: ()=>{},
       complete: ()=>{}
     });
    } catch (error) {
      console.log(error)
    }
  }

})

